package com.bang.daybreak.security.config.filter;

import com.bang.daybreak.common.util.JWTUtils;
import com.bang.daybreak.common.util.StringUtil;
import com.bang.daybreak.security.serivce.impl.MyUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 确保在一次请求只通过一次filter，而不需要重复执行。
 * </p>
 *
 * @version 1.0
 * @author: wdj
 * @date: 2019/8/11 0011 下午 18:02
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

//    @Qualifier("myUserDetailsServiceImpl")
    @Autowired
    private MyUserDetailsServiceImpl userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
            , FilterChain filterChain) throws ServletException, IOException {

        String authHeader = httpServletRequest.getHeader("Authorization");

        // TODO 先把权限关闭
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            final String authToken = authHeader.substring("Bearer ".length());
            String userId = JWTUtils.getUserId(authToken);
            if (StringUtil.isNotEmpty(userId)) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
                if (userDetails != null) {
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));

                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
